package com.juku2024.juku.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import com.juku2024.juku.model.NetworkEvent;
import com.juku2024.juku.tools.NetworkUtils;

import org.greenrobot.eventbus.EventBus;


public class NetStateChangeReceiver extends BroadcastReceiver {

    private NetworkType mType = NetworkUtils.INSTANCE.getNetworkType();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            NetworkType networkType = NetworkUtils.INSTANCE.getNetworkType();
            notifyObservers(networkType);
        }
    }

    private static class InstanceHolder {
        private static final NetStateChangeReceiver INSTANCE = new NetStateChangeReceiver();
    }


    public static void registerReceiver(Context context) {
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
    }

    public static void unRegisterReceiver(Context context) {
        context.unregisterReceiver(InstanceHolder.INSTANCE);
    }


    private void notifyObservers(NetworkType networkType) {
        if (mType == networkType) {
            return;
        }
        mType = networkType;
        if (networkType == NetworkType.NETWORK_NO) {
            EventBus.getDefault().post(new NetworkEvent(false));
        } else {
            EventBus.getDefault().post(new NetworkEvent(true));
        }
    }

}